﻿using MongoDB.Driver;
using Sustainalytics.Entities.RiskRatings;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Sustainalytics.RiskRatings.Service.Controllers.Company
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/v1/company/{companyId}")]
    public class LocationController : ApiController

    {
        private readonly IMongoCollection<EventIndicator> _eventCollection;
        private readonly IMongoCollection<Incident> _incidentCollection;

        public LocationController(IMongoCollection<EventIndicator> eventCollection, IMongoCollection<Incident> incidentCollection)
        {
            _eventCollection = eventCollection;
            _incidentCollection = incidentCollection;
        }

        [Route("event/{code}/locations")]
        public async Task<HttpResponseMessage> Get(Guid companyId, string code)
        {
            code = code.Replace("_", ".");
            var @event = await _eventCollection.Find(e => e.CompanyId == companyId && e.CanvasCode == code).FirstOrDefaultAsync().ConfigureAwait(false);

            if (@event == null)
                return Request.CreateResponse(System.Net.HttpStatusCode.NotFound);

            var locations = await _incidentCollection.Find(i => i.CompanyId == companyId && i.EventIndicatorId == @event.Id).Project(x => x.Location).ToListAsync().ConfigureAwait(false);

            return Request.CreateResponse(System.Net.HttpStatusCode.OK, locations.Distinct().ToList());
        }
    }
}